<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Muser extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
	 public function loginUser($uname, $upass)
    {
        
        $pass_encode = md5(md5($uname).md5($upass));
        
        $sql = $this->db->query("SELECT * FROM user WHERE username = '".strtolower($uname)."' AND password = '".$pass_encode."' ");
        $obj = $sql->row_object();
        if($sql->num_rows() > 0)
        {
             $data           = $sql->row();
             $data_ = array(
                'id_mem'             => $data->id,
                'username_mem'       => $uname,
                'fullname_mem'       => $data->fullname,
                'avatar'             => $data->avatar,
				'role'				 => 'member',
				'point'				 => $data->point,
				'email'				 => $data->email,
				'address'			 => $data->address,
				'mobile'			 => $data->mobile,
				'birthday'			 => $data->birthday,
                'flag'               => -1
            );
            if(in_array($obj->facebook, array(null, '')) && in_array($obj->google_plus, array(null, '')))
             {
                $data_['changepass'] = 1;
             }
            $this->session->set_userdata($data_);
            return 200;
        }else{
            return 201;
        }
    }
    
    public function getUser($id)
    {
        return $this->db->query('SELECT username, fullname, email, mobile, address, avatar, point, total_time FROM user WHERE id = '.$id.'')->row_object();
    }
    
    public function changePassDB()
    {
        $uname = $this->getParamString('username');
        $upassold = $this->getParamString('passwordold');
        $upassnew = $this->getParamString('passwordnew');
        $passwordcfr = $this->getParamString('passwordcfr');

        $pass_encode = md5(md5($uname).md5($upassold));
        
        $sql = $this->db->query("SELECT * FROM user WHERE username = '".strtolower($uname)."' AND password = '".$pass_encode."' ");
        if($sql->num_rows() > 0)
        {
            if($upassnew != $passwordcfr)
            {
                return 201;
            }
    
            $pass_en_code = md5(md5($uname).md5($upassnew));
            $data = array(
                'password'  => $pass_en_code
            );  
            $this->db->update('user', $data, "username = '".strtolower($uname)."'");
            return 200;
        }else{
            return 404;
        }

    }
    
    public function registerUser($username)
	{
	    $pass = $this->generateCode(6);
        $pass_encode = md5(md5($username).md5($pass));
        $qr = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($username).'"');
        $check = $qr->num_rows();
        
        if($check == 0)
        {
            $data = array(
                'username'  => $username,
                'password'  => $pass_encode
            );  
            $this->db->insert('user', $data);
	        $ID = $this->db->insert_id();
            $this->sendOTP($username, $pass);
            
            $_data = $this->db->query('SELECT * FROM user WHERE id = '.$ID)->row_object();
            $_data->password = null;
            $this->session->set_userdata(array('username' => $username));
            return 200;
        }else{
            $data = array(
                'password'  => $pass_encode
            );  
            $this->db->update('user', $data, "username = '".strtolower($username)."'");
            $this->sendOTP($username, $pass);
            $_data = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($username).'"')->row_object();
            $_data->password = null;
            $this->session->set_userdata(array('username' => $username));
            return 200;
        }   
	}
    
    
    public function forgotpassB()
    {
        $pass = rand(100000,999999);
        $uname = $this->getParamString('username');
        $pass_encode = md5(md5($uname).md5($pass));
        
        $qr = $this->db->query('SELECT * FROM user WHERE username = "'.strtolower($uname).'"');
        $check = $qr->num_rows();
        
        if($check > 0)
        {
            $data = array(
                'password'  => $pass_encode
            );  
            $this->db->update('user', $data, "username = '".strtolower($uname)."'");
            $this->sendOTP($uname, $pass, 1);
            return 200;
        }else{
            return 404;
        }
    }
    
    
    public function regDB($user, $passwd_new, $email, $fb = 0, $link_fb, $fullname, $profile_image)
    {
        $salt = $this->generateCode(6);
        
        if($user == '' || $passwd_new == '')
        {
            return (object)array('status' => '404');
        }
        if($this->alpha_dash($user) == 1 || $this->required($user) == 1 || $this->min_length($user, 5) == 1)
        {
            return (object)array('status' => '203');
        }
        
        $tr = $this->db->query('SELECT * FROM user WHERE LOWER(username) = "'.$user.'"')->num_rows();
        
        if($tr > 0)
        {
            if($fb == 1)
            {
                return (object)array('status' => '200', 'password' => $passwd_new);
            }else{
                return (object)array('status' => '201');   
            }
        }
        $pass_encode = md5(md5($user).md5($passwd_new));
        $data = array(
                'username'      => $user,
                'email'         => $email,
                'password'      => $pass_encode,
                'facebook'      => $link_fb,
                'fullname'      => $fullname,
                'avatar'        => $profile_image
                );
        $this->db->insert('user', $data);
        return (object)array('status' => '200', 'password' => $passwd_new);
    }
    
    
    public function regGoogleDB($user, $passwd_new, $email, $fb = 0, $link_google, $fullname, $profile_image)
    {//die($user.'-'.$passwd_new.'-'.$email.'-'.$fb.'-'.$link_google.'-'.$fullname.'-'.$profile_image);
        if($user == '' || $passwd_new == '')
        {
            return (object)array('status' => '404');
        }
        if($this->alpha_dash($user) == 1 || $this->required($user) == 1 || $this->min_length($user, 5) == 1)
        {
            return (object)array('status' => '203');
        }
        
        $tr = $this->db->query('SELECT * FROM user WHERE LOWER(username) = "'.$user.'"')->num_rows();
        
        if($tr > 0)
        {
            if($fb == 0)
            {
                return (object)array('status' => '200', 'password' => $passwd_new);
            }else{
                return (object)array('status' => '201');   
            }
        }
        
        $pass_encode = md5(md5($user).md5($passwd_new));
        $data = array(
                'username'      => $user,
                'email'         => $email,
                'password'      => $pass_encode,
                'google_plus'      => $link_google,
                'fullname'      => $fullname,
                'avatar'        => $profile_image
                );
        $this->db->insert('user', $data);
        
        return (object)array('status' => '200', 'password' => $passwd_new);
    }
    
    
    private function exNumberPhone($num)
    {
        return '84'.substr($num, 1);
    }
    
    private function sendOTP($dest, $otp, $types = 0)
    {
        if($types == 1)
        {
            $body = "VTV Now:\n Mat khau moi cua ban la: ".$otp;
        }else{
            $body = "VTV Now Code:\n Mat khau cua ban la: ".$otp;
        }
        $NumberPhone = $this->exNumberPhone($dest);
    	$moid = '0';
    	$moseq = '0';
    	$src = '8069';
    	$cmdcode = '';
    	$msgtype = 'Text';
    	$msgtitle = '';
    	$mttotalseg = '1';
    	$mtseqref = '1';
    	$procresult ='1';
	    $cpid = '10424';
    	$username = 'vtvd';
    	$password = 'vtvd#@$';
    	$WSDL = "http://agent.gapit.com.vn/AgentWS_SureM/SMSAgentWS.asmx?wsdl";
    	$client = new SoapClient($WSDL);
    	$mtseq = date('YmdHis').rand(0,999);
    
    	$data = array(
    		'mtseq'         =>    $mtseq,
    		'moid'          =>    $moid,
    		'moseq'         =>    $moseq,
    		'src'           =>    $src,
    		'dest'          =>    $NumberPhone,
    		'cmdcode'       =>    $cmdcode,
    		'msgbody'       =>    $body,
    		'msgtype'       =>    $msgtype,
    		'msgtitle'      =>    $msgtitle,
    		'mttotalseg'    =>    $mttotalseg,
    		'mtseqref'      =>    $mtseqref,
    		'cpid'          =>    $cpid,
    		'reqtime'       =>    date("d/m/Y h:i:s A"),
    		'serviceid'     =>    'Service01',
    		'procresult'    =>    $procresult,        
    		'username'      =>    $username,
    		'password'      =>    $password
    	);
    
    	$status = $client->SendMT($data);         
    }        
		
	public function ajaxupdateinfo(){
	
		$fullname = $this->getParamString('fullname');
		$email = $this->getParamString('email');
		$mobile = $this->getParamString('mobile');
		$address = $this->getParamString('address');
		
		$data = array (
			"fullname" => $fullname,
			"email" => $email,
			"mobile" => $mobile,
			"address" => $address
		);
		$run = $this->db->update('user', $data, "id =".$this->session->userdata('id_mem'));
		if($run){
			$data_ = array(
                'id_mem'             => $this->session->userdata('id_mem'),
                'username_mem'       => $this->session->userdata('username_mem'),
                'fullname_mem'       => $fullname,
                'avatar'             => $this->session->userdata('avatar')
            );
            $this->session->set_userdata($data_);
			return 200;
		}else{
			return 201;
		}
	}
    
    public function changepassUser($oldp,$newp)
    {
        $uname = $this->session->userdata('username_mem');
        $pass_encode = md5(md5($uname).md5($oldp));
        $sql = $this->db->query("SELECT * FROM user WHERE username = '".strtolower($uname)."' AND password = '".$pass_encode."' ");
        if($sql->num_rows() > 0)
        {    
            $pass_en_code = md5(md5($uname).md5($newp));
            $data = array(
                'password'  => $pass_en_code
            );  
            $this->db->update('user', $data, "id = '".$this->session->userdata('id_mem')."'");
            return 200;
        }else{
            return 404;
        }
    }    
    
    public function getStaticUser($id_user)
    {
        //die($id_user); ko dùng nữa
        $id_show = $this->db->query('SELECT id FROM tvshow_log')->result_object();
        $time_ = '';
        $point_ = '';
        $table_ = '';
        $where = '';
        $i = 1;
        foreach($id_show AS $el=>$le)
        {
            $time_ .= '+SUM(tv'.$i.'.time_total)';
            $point_ .= '+SUM(tv'.$i.'.point)';
            $table_ .= ',tvshow_statistics_'.$le->id.' AS tv'.$i;
            $where .= ' AND tv'.$i.'.user_id = '.$id_user;
            $i++;
        }
        
        $time = substr($time_, 1);
        $point = substr($point_, 1);
        $table = substr($table_, 1);
        
        $data = $this->db->query('SELECT ('.$time.') AS time, ('.$point.') AS point FROM '.$table.' WHERE 1=1 '.$where)->row_object();
        
        echo "<pre>";
        die(print_r($data));
        
    }
}